package com.neuedu.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.neuedu.pojo.SysUser;
import com.neuedu.service.ISysUserService;
import com.neuedu.util.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author liuyong
 * @since 2020-09-14
 */
@RestController
@RequestMapping("/sys-user")
public class SysUserController {

    @Resource
    ISysUserService sysUserService;
    @Resource
    BCryptPasswordEncoder encoder;
    @Resource
    RedisTemplate<String,String> redisTemplate;


//    //下面的可以了
    @PostMapping("/token")
    CommonResult token(SysUser user) throws JsonProcessingException {

        String token = sysUserService.token(user);
        if(StringUtils.isNotBlank(token)){
            return CommonResult.success(token);
        }else {
            return CommonResult.failed("登录失败");
        }

    }


    @GetMapping("/list")
    CommonResult list(SysUser user)
    {
        return CommonResult.success(sysUserService.list(user));
    }


    @PostMapping("/add")
    CommonResult add(SysUser user){
        user.setPassword(encoder.encode(user.getPassword()));
        user.setActive(1);
        if(sysUserService.add(user)){
            return CommonResult.success("ok");
        }else {
            return CommonResult.failed("用户名字已经存在");
        }
    }


    @GetMapping("/getById")
    CommonResult getById(Integer id){
        return CommonResult.success(sysUserService.getById(id));
    }

    @PostMapping("/update")
    CommonResult update(SysUser umsUser){
        umsUser.setPassword(encoder.encode(umsUser.getPassword()));
        return CommonResult.success(sysUserService.updateById(umsUser));
    }



    @PostMapping("/batchdel")
    CommonResult batchdel(Integer[] ids)
    {
        return CommonResult.success(sysUserService.batchdel(ids));
    }

    @PostMapping("/del")
    CommonResult del(SysUser umsUser){
        umsUser.setActive(0);
        return  CommonResult.success(sysUserService.updateById(umsUser));
    }

    @PostMapping("/back")
    CommonResult back(SysUser umsUser){
        umsUser.setActive(1);
        return  CommonResult.success(sysUserService.updateById(umsUser));
    }



}
